#!/usr/bin/python
# -*- coding: UTF-8 -*-

#bgr8 转 jpeg 格式

import os, sys
from time import sleep
try :
     import  netifaces
except  ImportError:
     try :
         command_to_execute  =  "pip install netifaces || easy_install netifaces"
         os.system(command_to_execute)
     except  OSError:
         print  "Can NOT install netifaces, Aborted!"
         sys.exit( 1 )
     import  netifaces
 
routingGateway  =  netifaces.gateways()[ 'default' ][netifaces.AF_INET][ 0 ]
routingNicName  =  netifaces.gateways()[ 'default' ][netifaces.AF_INET][ 1 ]
cmd = "iwconfig "+ routingNicName + " | grep \"ESSID:\" | awk -F\":\" \'{ print $2 }\' | cut -f1 -d\" \""
wifi_name_init = os.popen(cmd).read()

class WIFI_CONNECT:
    # 初始化函数
    def __init__(self,SSID,PASSWD):
        self.SSID = SSID
        self.PASSWD = PASSWD
        self.ip = '0.0.0.0'

    def connect(self):
        print("connect--------------")    
        if(self.SSID != '' and self.PASSWD != ''):
            passwd = "biowin"
            cmd_scan = "sudo iw dev" + routingNicName + "scan"
            os.system('echo %s | sudo -S %s' % (passwd, cmd_scan))
            cmd = "sudo nmcli dev wifi connect \'" + self.SSID + "\' password \'" + self.PASSWD + "\'"
            os.system('echo %s | sudo -S %s' % (passwd, cmd))

if __name__ == '__main__':
    while True:
        ssid = "biowin_2.4G"
        pwd = "birlbirl123"
        wifi = WIFI_CONNECT(ssid, pwd)
        wifi.connect()
        sleep(1)     
        if os.popen(cmd).read() !=  wifi_name_init:
            for  interface  in  netifaces.interfaces():
                if  interface  ==  routingNicName:
                    # print netifaces.ifaddresses(interface)
                    routingNicMacAddr  =  netifaces.ifaddresses(interface)[netifaces.AF_LINK][ 0 ][ 'addr' ]
                    try :
                        routingIPAddr  =  netifaces.ifaddresses(interface)[netifaces.AF_INET][ 0 ][ 'addr' ]
                        # TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
                        routingIPNetmask  =  netifaces.ifaddresses(interface)[netifaces.AF_INET][ 0 ][ 'netmask' ]
                    except  KeyError:
                        pass  
            with open("netconfig.txt","w") as f:
                f.write("routingGateway: "+routingGateway)
                f.write("\n")
                f.write("routingNicName: "+routingNicName)
                f.write("\n")
                f.write("routingNicMacAddr: "+routingNicMacAddr)
                f.write("\n")
                f.write("routingIPAddr: "+routingIPAddr)
                f.write("\n")
                f.write("routingIPNetmask: "+routingIPNetmask)
                f.write("\n")
                f.write("wifi_name: "+wifi_name)
            break 